/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webservices;

import Entities.Resource;
import Entities.User;
import constants.Consts;
import helpers.JsonHelper;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import org.codehaus.jettison.json.JSONException;
import security.Encryptor;

/**
 *
 * @author Bari
 */
public abstract class AbstractWebService {

    protected Encryptor encryptor;

    public AbstractWebService() throws Exception {
        encryptor = new Encryptor();
    }

    protected boolean messageGenuine(String msg, String signature) {
       
        
        
////TODO whf is going on here
//        int hashcode = msg.hashCode();
//        int signHashCode = -1;
//        try {
//            signHashCode = Integer.parseInt(encryptor.rsaDecrypt(signature));
//        } catch (Exception ex) {
//            Logger.getLogger(AbstractWebService.class.getName()).log(Level.SEVERE, null, ex);
//        }
//          return (hashcode==signHashCode);
        return true;
    }
    
    
     protected User getLocalUser(String androidId, EntityManager em) {
        TypedQuery<User> query = em.createNamedQuery("User.findByIdentifier", User.class);
        query.setParameter("identifier", androidId);
        List<User> users = query.getResultList();
        if (users.size() > 0) {
            return users.get(0);
        } else {

            EntityTransaction tx = em.getTransaction();
            tx.begin();
            User user = new User();
            user.setIdentifier(androidId);
            em.persist(user);
            em.getTransaction().commit();
            return user;
        }
    }
     
      protected Resource getResourceById(long resourceId, EntityManager em) {
        TypedQuery<Resource> query = em.createNamedQuery("Resource.findById", Resource.class);
        query.setParameter("id", resourceId);
        List<Resource> resources = query.getResultList();
        if (resources.size() > 0) {
            return resources.get(0);
        } else {
             return null;
        }
    }
    

    @POST
    @Produces("application/json")
    public String getJson(@FormParam(Consts.PARAM_MESSAGE) String jsonMsg, @FormParam(Consts.PARAM_SIGNATURE) String signature) throws JSONException {

        if (messageGenuine(jsonMsg, signature)) {
            return processJsonMessage(jsonMsg);
        } else {
            return JsonHelper.createErrorResponseJson(jsonMsg);
        }
    }

    protected abstract String processJsonMessage(String jsonMessage);
    


   
}
